package com.example.leero.graduation.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.leero.graduation.API;
import com.example.leero.graduation.App;
import com.example.leero.graduation.BaseActivity;
import com.example.leero.graduation.R;
import com.example.leero.graduation.Util.GsonUtil;
import com.example.leero.graduation.Util.ImageLoader;
import com.example.leero.graduation.Util.LogUtil;
import com.example.leero.graduation.Util.StringUtil;
import com.example.leero.graduation.adapter.ActivityAdapter;
import com.example.leero.graduation.customView.LoadingDialog;
import com.example.leero.graduation.model.ActItem;
import com.example.leero.graduation.model.User;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.zhy.adapter.recyclerview.wrapper.HeaderAndFooterWrapper;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import okhttp3.Call;

public class HomeActivity extends BaseActivity implements View.OnClickListener {

    // Home View
    private ImageButton iv_left, btn_rank, btn_search, btn_punch, btn_run, btn_publish_act;
    private ImageView iv_avatar;  // 头像
    private TextView tv_title;
    private SlidingMenu menu;
    private RecyclerView activities_list;
    private SwipeRefreshLayout refreshLayout;
    private List<ActItem> itemData = new ArrayList();
    private HeaderAndFooterWrapper wrapper;

    // Menu View
    private ImageView menuAvatar, menuSex;
    private  TextView menuUserName, menuUserSignature, menuPublishNum, menuJoinNum, menuLevel;

    private Boolean isSearch = false;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_home;
    }

    @Override
    protected void initView(Bundle state) {
        initHomeView();
        initMenu();
        initMenuView();

        getActiveData();

        iv_avatar.setOnClickListener(this);
        btn_search.setOnClickListener(this);
        btn_run.setOnClickListener(this);
        btn_publish_act.setOnClickListener(this);
        btn_rank.setOnClickListener(this);
        btn_punch.setOnClickListener(this);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getActiveData();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkUserState();
        if(!isSearch) {
            getActiveData();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        switch(requestCode) {
            case 1:
                if (intent != null) {
                    isSearch = intent.getBooleanExtra("isSearch", false);
                    itemData.clear();
                    itemData.addAll((Collection<? extends ActItem>) intent.getSerializableExtra("actItem"));
                    wrapper.notifyDataSetChanged();
                }
                break;
            default:
                break;
        }
    }

    private void initHomeView() {
        btn_search = (ImageButton) findViewById(R.id.btn_search);
        iv_avatar = (ImageView) findViewById(R.id.iv_avatar);
        iv_left = (ImageButton) findViewById(R.id.iv_left);
        tv_title = (TextView) findViewById(R.id.tv_title);
        activities_list = (RecyclerView) findViewById(R.id.activity_list);
        refreshLayout = (SwipeRefreshLayout) findViewById(R.id.refresh_layout);
        setupRV();

        iv_left.setVisibility(View.INVISIBLE);
        iv_avatar.setVisibility(View.VISIBLE);
        btn_search.setVisibility(View.VISIBLE);
        tv_title.setText("动么");
    }

    private void initMenuView() {
        menuAvatar = (ImageView) menu.findViewById(R.id.iv_avatar);
        menuSex = (ImageView) menu.findViewById(R.id.iv_me_sex);
        menuUserName = (TextView) menu.findViewById(R.id.tv_username);
        menuUserSignature = (TextView) menu.findViewById(R.id.tv_frd_sign);
        menuPublishNum = (TextView) menu.findViewById(R.id.tv_friend_detail_release_count);
        menuJoinNum = (TextView) menu.findViewById(R.id.tv_friend_detail_join_count);
        menuLevel = (TextView) menu.findViewById(R.id.tv_me_level);
    }

    private void handleUser(User user) {
        if (!StringUtil.isEmpty(user.user_icon)) {
            ImageLoader.load(this, iv_avatar, user.user_icon);
            ImageLoader.load(this, menuAvatar, user.user_icon);
        } else {
            iv_avatar.setImageResource(R.drawable.default_avatar_cricle);
        }

        if(user.sex == 0) {
            menuSex.setImageResource(R.drawable.draw_women);
        } else {
            menuSex.setImageResource(R.drawable.draw_man);
        }

        menuUserName.setText(user.nickname);
        menuLevel.setText("lv." + getIntegralLevel(user.integral));
        menuUserSignature.setText(StringUtil.isEmpty(user.per_signature) ? "这人很懒，什么也没留下..." : user.per_signature);
        menuPublishNum.setText("发布("+user.publish_num + ")");
        menuJoinNum.setText("参加(" + user.join_num + ")");
    }

    private void setupRV() {
        activities_list.setLayoutManager(new LinearLayoutManager(this));
        View view = getLayoutInflater().inflate(R.layout.header_home, activities_list, false);
        initHeader(view);
        wrapper = new HeaderAndFooterWrapper(new ActivityAdapter(this, itemData));
        wrapper.addHeaderView(view);
        activities_list.setAdapter(wrapper);
    }

    private void initHeader(View view) {
        btn_run = (ImageButton) view.findViewById(R.id.btn_run);
        btn_publish_act = (ImageButton) view.findViewById(R.id.btn_publish_act);
        btn_rank = (ImageButton) view.findViewById(R.id.btn_rank);
        btn_punch = (ImageButton) view.findViewById(R.id.btn_punch);
    }

    /**
     * 获取首页活动list
     */
    private void getActiveData() {
        OkHttpUtils
                .post()
                .url(API.GET_ALL_ACTIVITIES)
                .addParams("page", "1")
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        itemData.clear();
                        itemData.addAll(GsonUtil.jsonToArrayList(GsonUtil.getData(response), ActItem.class));
                        wrapper.notifyDataSetChanged();
                    }

                    @Override
                    public void onAfter(int id) {
                        refreshLayout.setRefreshing(false);
                    }
                });
    }

    /**
     *  初始化侧滑菜单
     */
    private void initMenu() {
        menu = new SlidingMenu(this);
        menu.setMode(SlidingMenu.LEFT); // 菜单靠左
        menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN); // 支持全屏滑动范围
        menu.setBehindOffset(200); // 设置滑动菜单出来之后，内容页显示的剩余宽度
        menu.setShadowDrawable(R.drawable.left_shadow); // 设置拉出时阴影
        menu.setFadeDegree(0.4f); // 设置拉出时淡入淡出
        menu.setOffsetFadeDegree(0.4f); // 设置剩余的淡入淡出
        menu.setMenu(R.layout.fragment_me);
        menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);

        menu.findViewById(R.id.go_edit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(HomeActivity.this, EditActivity.class);
                startActivity(intent);
            }
        });

        menu.findViewById(R.id.go_setting).setOnClickListener(this);
        menu.findViewById(R.id.tv_feedback).setOnClickListener(this);
        menu.findViewById(R.id.rl_release_container).setOnClickListener(this);
        menu.findViewById(R.id.rl_join_container).setOnClickListener(this);
        menu.findViewById(R.id.btn_intergral).setOnClickListener(this);
        menu.findViewById(R.id.btn_attention).setOnClickListener(this);
    }

    private int getIntegralLevel(int integral) {
        if (integral <= 50) return 1;
        if (integral >= 51 && integral <= 110) return 2;
        if (integral >= 111 && integral <= 170) return 3;
        if (integral >= 171 && integral <= 240) return 4;
        if (integral >= 241 && integral <= 320) return 5;
        if (integral >= 321 && integral <= 410) return 6;
        if (integral >= 411 && integral <= 510) return 7;
        if (integral >= 511 && integral <= 650) return 8;
        if (integral >= 651 && integral <= 800) return 9;
        if (integral >= 801) return 10;
        return 0;
    }

    /**
     * 检查user状态
     */
    private void checkUserState() {
        if(!App.isLogin()) {
            return;
        }
        OkHttpUtils.get().url(API.GET_USER)
                .addParams("user_id", App.getLoginUser().id + "")
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    User user = GsonUtil.fromJson(jsonObject.getString("user"), User.class);
                    App.updateUser(user);
                    handleUser(user);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 请求打卡
     */
    private void punch() {
        OkHttpUtils.post().url(API.PUNCH_CLOCK2)
                .addParams("user_id", App.getLoginUser().id+"")
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getBoolean("state")) {
                        new AlertDialog.Builder(HomeActivity.this)
                                .setMessage("签到成功！")
                                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        checkUserState();
                                    }
                                })
                                .show();
                    } else {
                        new AlertDialog.Builder(HomeActivity.this)
                                .setMessage(jsonObject.getString("message"))
                                .setPositiveButton("确认", null)
                                .show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onAfter(int id) {
                LoadingDialog.dismissDialog();
            }
        });
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.iv_avatar:
                menu.toggle();
                break;
            case R.id.btn_search:
                // 跳转搜索页面
                intent.setClass(this, SearchActivity.class);
                startActivityForResult(intent, 1);
                break;
            case R.id.btn_rank:
                // 跳转至排名页面
                intent.setClass(this, RankActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_punch:
                // 打卡
                LoadingDialog.show(this);
                post(new Runnable() {
                    @Override
                    public void run() {
                        punch();
                    }
                }, 1000);
                break;
            case R.id.go_setting:
                // 设置
                intent.setClass(this, SettingActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_feedback:
                // 反馈
                intent.setClass(this, FeedBackActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_run:
                // 跑步
                intent.setClass(this, RunActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_publish_act:
                // 发布活动
                intent.setClass(this, PublishActivity.class);
                startActivity(intent);
                break;
            case R.id.rl_release_container:
                intent.setClass(this, UserPublishActivity.class);
                intent.putExtra("user_id", App.getLoginUser().id);
                startActivity(intent);
                break;
            case R.id.rl_join_container:
                intent.setClass(this, UserJoinActivity.class);
                intent.putExtra("user_id", App.getLoginUser().id);
                startActivity(intent);
                break;
            case R.id.btn_intergral:
                intent.setClass(this, IntegralActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_attention:
                intent.setClass(this, FavourSportActivity.class);
                startActivity(intent);
            default: break;
        }
    }

    /**
     * 禁止系统返回键
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return false;
    }
}
